/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package isnmp.ui;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;

import sg.simple.snmp.provider.NetMapException;

public class RemoteLogin {

	Logger logger = Logger.getLogger(RemoteLogin.class);

	// system32/mstsc.exe
	private static String REMOTE_DESKTOP_PROGRAM_PATH = File.separator
			+ "system32" + File.separator + "mstsc.exe";

	public void login() throws IOException {
		Runtime r = Runtime.getRuntime();
		Process p = null;
		try {
			// %SystemRoot%\system32\mstsc.exe
			File[] roots = File.listRoots();
			for (File root : roots) {
				File file = new File(root.getAbsolutePath()
						+ "\\WINDOWS\\system32");
				if (file.exists()) {
					p = r.exec(file.getAbsolutePath() + "\\mstsc.exe");

				}
			}
		} catch (Exception e) {
			logger.error("unable to execute remote loggin program", e);
		}
	}

	public void login(String ipAddress) throws NetMapException {

		ProcessBuilder processBuilder = new ProcessBuilder(
				locateRemoteDesktop(), "/v:" + ipAddress);
		

		try {
			processBuilder.start();
		} catch (IOException exception) {
			logger.error("Unable to start remote desktop", exception);
			throw new NetMapException("Unable to start remote desktop",
					exception);
		}
	}

	private String locateRemoteDesktop() throws NetMapException {

		String windowsDirectory = System.getenv("windir");
		if (windowsDirectory == null || windowsDirectory.trim().length() == 0) {
			throw new NetMapException("Unable to locate windows directory");
		}

		String absPathToRemoteDesktop = windowsDirectory.trim()
				+ REMOTE_DESKTOP_PROGRAM_PATH;
		if (!new File(absPathToRemoteDesktop).exists()) {
			throw new NetMapException(
					"Unable to locate remote desktop program in - "
							+ absPathToRemoteDesktop);
		}

		return absPathToRemoteDesktop;

	}

}